<script setup lang="ts">
import {ref, onMounted, computed} from 'vue';
import {Avatar, Card, Tag, Tooltip, Button, Divider, Statistic, Row, Col, Descriptions, message} from 'ant-design-vue';
import {
  ArrowLeftOutlined,
  ShareAltOutlined,
  MessageOutlined,
  UserAddOutlined,
  LikeOutlined,
  StarOutlined,
  EyeOutlined
} from '@ant-design/icons-vue';
import router from '@/router';
import dayjs from 'dayjs';
import {useLoginUserStore} from '@/stores/useLoginUserStore';
import UserVO = API.UserVO;
import {followUser, getUserById} from "@/api/userController.ts";
import {useRoute} from "vue-router";
import UserDetailVO = API.UserDetailVO;
import {getRecentBlogVoList} from "@/api/blogController.ts";

// 模拟用户数据，根据用户提供的格式
// const userDetail = ref({
//   id: "13",
//   userAccount: "user13",
//   username: "无名13",
//   userAvatar: "https://cloud-picture-1361877603.cos.ap-guangzhou.myqcloud.com/public/1/2025-09-11_ze1A7F3vUcHALYrf.webp",
//   userProfile: "大家嚎",
//   userTags: ["qwq"],
//   teach: ["音乐", "美术"],
//   learn: ["六级", "雅思"],
//   userRole: "user",
//   status: 1,
//   points: 0,
//   blogCount: 0,
//   blogTotalView: "0",
//   likeCount: 0,
//   collectCount: 0,
//   followCount: 0,
//   fanCount: 0,
//   createTime: "2025-09-14T05:06:39.000+00:00",
//   updateTime: "2025-09-22T07:35:00.000+00:00"
// });
const userDetail = ref<UserDetailVO>({})

const route = useRoute();
const userData = ref<UserVO>({})
const recentActivities = ref([])

const loginUserStore = useLoginUserStore();
const isFollowing = ref(false);

// 返回上一页
const goBack = () => {
  router.back();
};

// 关注用户
const handleFollow = async () => {
  const res = await followUser({
    userId: loginUserStore.loginUser.id,
    followedId: route.params.id,
    isFollow: userDetail.value.isFollow
  })
  if (res.data.code === 0 && res.data.data) {
    userDetail.value.isFollow = !userDetail.value.isFollow;
    if (userDetail.value.isFollow) {
      userDetail.value.followCount++;
    } else {
      userDetail.value.followCount--;
    }
    if (userDetail.value.isFollow) {
      message.success('关注成功')
    } else {
      message.success('取消关注成功')
    }
  } else {
    message.error('关注失败，' + res.data.message)
  }

};


//获取用户信息
const fetchUserData = async () => {
  // 获取用户信息
  const res = await getUserById({
    id: route.params.id
  })
  if (res.data.code === 0 && res.data.data) {
    userDetail.value = res.data.data;
    console.log('获取用户信息成功，', res.data.data)
  } else {
    message.error("获取用户信息失败，" + res.data.message)
  }
}
// 分享功能
const handleShare = async () => {
  try {
    // 获取当前页面的URL
    const currentUrl = window.location.href;
    console.log(getCookie('JSESSIONID'))

    // 复制URL到剪切板
    await navigator.clipboard.writeText(currentUrl);

    // 显示复制成功提示
    message.success('链接已复制到剪贴板');
  } catch (err) {
    console.error('复制失败:', err);
    message.error('复制失败，请手动复制链接');
  }
}


const getCookie = (name) => {
  // 1. 将cookie字符串分割成数组
  const cookies = document.cookie.split(';');
  console.log("cookies:" + cookies)

  // 2. 遍历所有cookie
  for (let cookie of cookies) {
    // 3. 去除空格并分割键值对
    const [cookieName, cookieValue] = cookie.trim().split('=');

    // 4. 如果找到目标cookie则返回其值
    if (cookieName === name) {
      return decodeURIComponent(cookieValue); // 解码URI编码的值
    }
  }

  // 5. 未找到则返回null
  return null;
}

// 发送私信
const sendPrivateMessage = () => {
  const userId = route.params.id;
  router.push(`/chat?id=${userId}&type=user`)
}

const session = computed(() => {
  getCookie('SESSION')
})
console.log("session:" + session)

//获取近期活动
const fetchRecentActivities = async () => {
  const res = await getRecentBlogVoList({
    id: route.params.id
  })
  if (res.data.code === 0 && res.data.data) {
    recentActivities.value = res.data.data;
  } else {
    message.error("获取近期活动失败，" + res.data.message)
  }
}

// 格式化内容，去除HTML标签并截取长度
const formatContent = (content) => {
  // 简单处理，实际项目中可能需要更复杂的处理
  if (!content) return '';
  const text = content.replace(/<[^>]*>/g, '');
  return text.length > 100 ? text.substring(0, 100) + '...' : text;
};

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm');
};

// 跳转到博客详情页
const navigateToBlog = (blogId) => {
  router.push({
    path: `/blog/${blogId}`
  });
};

onMounted(() => {
  fetchUserData()
  fetchRecentActivities()
});
</script>

<template>
  <div id="UserDetailPage">
    <div class="user-detail-container">
      <!-- 返回按钮 -->
      <div class="back-button-container">
        <a-button type="text" @click="goBack">
          <template #icon>
            <ArrowLeftOutlined/>
          </template>
          返回
        </a-button>
      </div>


      <!-- 用户头部信息 -->
      <div class="user-header">
        <Avatar :src="userDetail.userVO?.userAvatar" size="large"/>

        <div class="user-name-section">
          <div class="username-container">
            <h1 class="username">{{ userDetail.userVO?.username }}</h1>
            <Tag v-if="userDetail.userVO?.userRole === 'admin'" color="red">管理员</Tag>
            <Tag v-else color="blue">用户</Tag>
            <div class="user-actions">
              <a-button
                  :type="userDetail.isFollow ? 'default' : 'primary'"
                  @click="handleFollow"
                  class="follow-button"
              >
                <template #icon>
                  <UserAddOutlined/>
                </template>
                {{ userDetail.isFollow ? '已关注' : '关注' }}
              </a-button>

              <a-button
                  type="default"
                  class="message-button"
                  @click="sendPrivateMessage"
              >
                <template #icon>
                  <MessageOutlined/>
                </template>
                发私信
              </a-button>

              <a-button
                  type="default"
                  class="share-button"
                  @click="handleShare"
              >
                <template #icon>
                  <ShareAltOutlined/>
                </template>

                分享
              </a-button>
            </div>
          </div>
          <div class="user-basic-info">
            <span>账号: {{ userDetail.userVO?.userAccount }}</span>
          </div>
        </div>
      </div>

      <Divider/>

      <!-- 用户简介 -->
      <div class="user-profile-section">
        <h2 class="section-title">个人简介</h2>
        <p class="user-profile">{{ userDetail.userVO?.userProfile }}</p>
      </div>

      <!-- 用户基本数据统计 -->
      <div class="user-stats-summary">
        <div class="stat-item">
          <div class="stat-value">{{ userDetail.userVO?.blogCount }}</div>
          <div class="stat-label">博客</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ userDetail.userVO?.likeCount }}</div>
          <div class="stat-label">获赞</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ userDetail.userVO?.followCount }}</div>
          <div class="stat-label">关注</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ userDetail.userVO?.fanCount }}</div>
          <div class="stat-label">粉丝</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ userDetail.userVO?.points }}</div>
          <div class="stat-label">积分</div>
        </div>
      </div>


      <!-- 用户标签和技能 -->
      <div class="skills-tags-section">
        <!-- 个人标签 -->
        <Card class="skills-tags-card" title="个人标签">
          <div class="tags-container">
            <Tag v-for="tag in userDetail.userVO?.userTags || []" :key="tag" class="user-tag">
              {{ tag }}
            </Tag>
            <div v-if="!userDetail.userVO?.userTags?.length" class="empty-tags">
              暂无标签
            </div>
          </div>
        </Card>

        <!-- 擅长技能 -->
        <Card class="skills-tags-card" title="擅长技能">
          <div class="tags-container">
            <Tag v-for="skill in userDetail.userVO?.teach" :key="skill" color="green" class="skill-tag">
              {{ skill }}
            </Tag>
            <div v-if="userDetail.userVO?.teach.length === 0" class="empty-tags">
              暂无技能
            </div>
          </div>
        </Card>

        <!-- 学习需求 -->
        <Card class="skills-tags-card" title="学习需求">
          <div class="tags-container">
            <Tag v-for="learn in userDetail.userVO?.learn" :key="learn" color="orange" class="skill-tag">
              {{ learn }}
            </Tag>
            <div v-if="userDetail.userVO?.learn.length === 0" class="empty-tags">
              暂无学习需求
            </div>
          </div>
        </Card>
      </div>


      <!-- 近期活动 -->
      <Card class="activities-card" title="近期活动">
        <div v-if="recentActivities.length === 0" class="empty-activities">
          暂无活动记录
        </div>
        <div v-else class="activities-list">
          <div v-for="activity in recentActivities" :key="activity.id" class="activity-item"
               @click="navigateToBlog(activity.id)">
            <div class="activity-header">
              <h3 class="activity-title">{{ activity.title }}</h3>
              <div class="activity-tags">
                <Tag v-for="tag in activity.tags" :key="tag" class="activity-tag">
                  {{ tag }}
                </Tag>
              </div>
            </div>
            <div class="activity-content" v-html="formatContent(activity.content)"></div>
            <div class="activity-footer">
              <div class="activity-time">{{ formatTime(activity.createTime) }}</div>
              <div class="activity-stats">
                <span class="stat-item">
                  <LikeOutlined :class="{ 'liked': activity.isLiked }"/>
                  {{ activity.likeNum }}
                </span>
                <span class="stat-item">
                  <StarOutlined :class="{ 'collected': activity.isCollected }"/>
                  {{ activity.collectNum }}
                </span>
                <span class="stat-item">
                  <EyeOutlined/>
                  {{ activity.viewCount }}
                </span>
                <span class="stat-item">
                  <MessageOutlined/>
                  {{ activity.commentCount }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </Card>
    </div>
  </div>
</template>

<style scoped>
#UserDetailPage {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 24px 0;
}

.user-detail-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 32px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.back-button-container {
  margin-bottom: 24px;
}

.user-header {
  display: flex;
  align-items: center;
  gap: 24px;
  margin-bottom: 32px;
}

.user-name-section {
  flex: 1;
}

.username-container {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.username-container .user-actions {
  margin-left: auto;
  display: flex;
  gap: 8px;
}

.username {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.user-basic-info {
  display: flex;
  gap: 24px;
  font-size: 14px;
  color: #666;
  flex-wrap: wrap;
}

.user-profile-section {
  margin-bottom: 32px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.user-profile {
  font-size: 16px;
  line-height: 1.8;
  color: #666;
  margin: 0;
}

.user-stats-summary {
  display: flex;
  justify-content: space-around;
  padding: 24px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 24px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #1890ff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.user-actions {
  display: flex;
  gap: 12px;
}

.follow-button {
  min-width: 100px;
}

.message-button {
  min-width: 100px;
}

.share-button {
  min-width: 80px;
}

.user-info-card {
  margin-bottom: 24px;
}

.skills-tags-section {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 24px;
  margin-bottom: 24px;
}

.skills-tags-card {
  min-height: 120px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  min-height: 32px;
  align-items: center;
}

.user-tag {
  font-size: 14px;
  padding: 4px 12px;
}

.skill-tag {
  font-size: 14px;
  padding: 4px 12px;
}

.empty-tags {
  color: #999;
  font-size: 14px;
  padding: 4px 0;
}

.stats-card {
  margin-bottom: 24px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-card-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
}

.stat-card-icon {
  font-size: 24px;
  color: #1890ff;
  margin-bottom: 8px;
}

.stat-card-value {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.stat-card-label {
  font-size: 14px;
  color: #666;
}

.activities-card {
  margin-bottom: 24px;
}

.activities-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.activity-item {
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.activity-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-color: #1890ff;
}

.activity-item:active {
  transform: scale(0.98);
}

.activity-header {
  margin-bottom: 12px;
}

.activity-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
}

.activity-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.activity-tag {
  font-size: 12px;
  background-color: #f0f0f0;
}

.activity-content {
  font-size: 14px;
  line-height: 1.6;
  color: #666;
  margin-bottom: 12px;
}

.activity-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.activity-time {
  font-size: 12px;
  color: #999;
}

.activity-stats {
  display: flex;
  gap: 16px;
}

.activity-stats .stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.activity-stats .stat-item .anticon {
  font-size: 12px;
}

.activity-stats .stat-item .liked {
  color: #ff4d4f;
}

.activity-stats .stat-item .collected {
  color: #faad14;
}

.empty-activities {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 150px;
  color: #999;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-detail-container {
    padding: 16px;
  }

  .user-header {
    flex-direction: column;
    align-items: center;
    text-align: center;
    gap: 24px;
  }

  .username-container {
    justify-content: center;
    flex-direction: column;
  }

  .username-container .user-actions {
    margin-left: 0;
    margin-top: 12px;
    justify-content: center;
  }

  .user-basic-info {
    justify-content: center;
  }

  .user-stats-summary {
    justify-content: center;
    gap: 32px;
    flex-wrap: wrap;
  }

  .user-actions {
    justify-content: center;
    flex-wrap: wrap;
  }

  .skills-tags-section {
    grid-template-columns: 1fr;
  }

  .stats-card .ant-row {
    .ant-col {
      margin-bottom: 16px;
    }
  }

  .activity-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .activity-stats {
    width: 100%;
    justify-content: space-between;
  }

  .activity-title {
    font-size: 16px;
  }
}
</style>
